package com.study.system.controller;

import cn.hutool.json.JSONUtil;
import com.study.system.common.result.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/websocket")
@RequiredArgsConstructor
@Slf4j
public class WebsocketController {

    private final SimpMessagingTemplate messagingTemplate;


    @PostMapping("/sendToAll")

    public Result sendToAll(String message) {
        log.info("【广播消息请求接收】消息：{}", message);




        String content = "服务端广播消息： " + message;


        messagingTemplate.convertAndSend("/topic/all", content);

        return Result.success("广播消息发送成功");
    }


    @PostMapping("/sendToUser/{userId}")
    public Result sendToUser(@PathVariable Long userId, String message) {
        log.info("【点对点请求接收】用户：{};消息：{}", userId, JSONUtil.toJsonStr(message));

        messagingTemplate.convertAndSendToUser(String.valueOf(userId), "/message", message);
        return Result.success("点对点消息发送成功");
    }

}
